#include "mainuiloader.h"

#include <QDebug>
#include <QMessageBox>
#include <QFile>
#include <QApplication>

#include "confirmdialog.h"
#include "mainwindow.h"

const QString DefaultPasswordFileName = "passwd.h";
MainWindow *w;

MainUILoader::MainUILoader(QWidget *parent) :
    QWidget(parent)
{  
    if(!loadPasswdFile(DefaultPasswordFileName))
    {
        QMessageBox::critical(this,tr("Ignition Control"),
                              tr("Error in %1\n"
                                 "Application must quit"
                              ).arg(DefaultPasswordFileName),
                              QMessageBox::Abort);
        //qApp->exit(-1);
        exit(-1);
        return;
    }

    ConfirmDialog cc;
    cc.setPasswordFileName(DefaultPasswordFileName);
    cc.setUnlockPassword(unlockPasswd);
    cc.setIgnitionPassword(ignitionPasswd);
    if(cc.exec() != QDialog::Accepted)
    {
        //qApp->exit(-1);
        exit(-1);
        return;
    }

    w = new MainWindow;
    w->setUnlockPassword(unlockPasswd);
    w->setIgnitionPassword(ignitionPasswd);
    w->show();
}

MainUILoader::~MainUILoader()
{
    delete w;
}

bool MainUILoader::loadPasswdFile(QString fileName)
{
    QFile pwfile(fileName);
    if(!pwfile.open(QIODevice::ReadOnly))
         return false;

    QString pwinfo;
    pwinfo.append(QByteArray(pwfile.readAll()));
    pwfile.close();

    QStringList pwlist = pwinfo.split(';');

    unlockPasswd = "";
    ignitionPasswd = "";

    pwlist.removeDuplicates();
    pwlist.replaceInStrings(" ","");
    foreach(const QString &pwitem , pwlist)
    {
        if(pwitem.startsWith("#")
         ||pwitem.startsWith("//")
         ||pwitem.startsWith("/*"))
            continue;

        if(pwitem.contains("unlock_key"))
            unlockPasswd = pwitem.section('\"',1,1);
        if(pwitem.contains("ignition_key"))
            ignitionPasswd = pwitem.section('\"',1,1);
    }

    bool pwValid = true;

    if(unlockPasswd.length() != ignitionPasswd.length())
        pwValid = false;

    for(int i=0;i<unlockPasswd.length();i++)
    {
        QChar c = unlockPasswd.at(i);
        if(!c.isDigit() && !c.isLower())
        {pwValid = false;break;}
    }

    for(int i=0;i<ignitionPasswd.length();i++)
    {
        QChar c = ignitionPasswd.at(i);
        if(!c.isDigit() && !c.isLower())
        {pwValid = false;break;}
    }

    //qDebug() << unlockPasswd;
    //qDebug() << ignitionPasswd;

    return pwValid;
}
